package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {



    @Autowired
    RedisTemplate<String,String>redisTemplate;

    /**
     * 用户关注/取消关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDTO dto) {

        //TODO 1、检查参数
        //todo 1.1、查看用户是否登录
        ApUser loginApUser = AppThreadLocalUtils.getUser();
        if (loginApUser==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户未登录");
        }
        //todo 1.2、判断operstion的值  0关注  1取消关注
        Short operation = dto.getOperation();
        if (operation==null||(operation.intValue()!=0&&operation.intValue()!=1)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"关注类型错误");
        }
        //todo 1.3、 自己不能关注自己
        Integer userId = loginApUser.getId();//获取登录用户id
        Integer authorApUserId = dto.getAuthorApUserId();//获取文章作者id
        if (userId.equals(authorApUserId)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"此操作不被允许，自己不可关注自己");
        }
        //todo 判断是否已经关注过
        ZSetOperations<String, String> zScore = redisTemplate.opsForZSet();
        //zscore  follow
        //参数1;key 参数2 ：要查询集合元素
        zScore.score(UserRelationConstants.FOLLOW_LIST+userId,String.valueOf(authorApUserId));
        if (operation.intValue()==0&&zScore!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"你已关注，请勿重复操作");
        }
        try {
            //TODO 2、关注作者
            //TODO 开启redis 事务管理
            redisTemplate.multi();
            if (operation.intValue()==0){
                //todo 关注 zadd follow :用户id 作者id 关注时间
                zScore.add(UserRelationConstants.FOLLOW_LIST+userId,String.valueOf(authorApUserId),System.currentTimeMillis());
                //todo 被关注 zadd fans：作者id 关注者的id 被关注时间
                zScore.add(UserRelationConstants.FANS_LIST+authorApUserId,String.valueOf(userId),System.currentTimeMillis());
            }else {
                //TODO 3、取关作者 operation=1
                //    zrem  follow:我的id   作者id
               zScore.remove(UserRelationConstants.FOLLOW_LIST+userId,String.valueOf(authorApUserId),System.currentTimeMillis());
               //todo zrem  fans:作者id    我的id
                zScore.remove(UserRelationConstants.FANS_LIST+authorApUserId,String.valueOf(userId),System.currentTimeMillis());
            }
            //TODO 提交事务
            redisTemplate.exec();
        } catch (Exception e) {
            e.printStackTrace();
            //todo 有异常取消事务
            redisTemplate.discard();
            log.error("关注或取关异常，异常原因:{}",e.getMessage());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"关注或取关异常");
        }
        return ResponseResult.okResult();
    }
}
